﻿/*
 * 文件名称：
 * 程序员：huangsb
 * 创建时间：2008/06/10
 * 
 * 功能说明：模板标签管理
 * 
 * 修改人员：
 * 
 * 修改日期：
 *      2008/06/25
 *      
 * 修改记录：
 *      1.增加设计视图
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Whir.Common;
using Whir.Common.WebHelper;

public partial class Whir_System_Module_Template_TemplateLabel : System.Web.UI.Page
{
    protected string dir = "";
    protected string sysPath = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        sysPath = Settings.GetString("SystemPath");

        this.dir = Request.QueryString["dir"].ToString();

        if (!IsPostBack)
        {
            StreamReader sr = new StreamReader(dir, Encoding.UTF8);

            this.txtHtml.Text = sr.ReadToEnd();

            sr.Close();
            BindLabel();
            BindHistory();
        }
    }

    private void BindHistory()
    {
        ArrayList list = FileBackupHelper.ListHistory(Page, this.dir);
        if (list.Count == 0)
        {
            list.Add("暂无记录");
            btnRestore.Enabled = false;
        }
        ddlHistory.DataSource = list;
        ddlHistory.DataBind();
    }

    #region 标签定位
    //绑定固定标签
    protected void BindLabel()
    {
        this.Literal1.Text = "";

        //搜索固定标签
        Regex rg = new Regex(@"\{Whir\.Label\.[a-zA-Z]{1,}\/\}");
        MatchCollection mcs = rg.Matches(this.txtHtml.Text);

        for (int i = 0; i < mcs.Count; i++)
        {
            string mark = "";
            //判断同一标签出现的次数
            int k = 0;
            for (int j = 0; j < i; j++)
            {
                if (mcs[i].Value == mcs[j].Value)
                    k++;
            }
            if (k > 0)
                mark = "_" + Convert.ToString(k + 1);

            this.Literal1.Text += "<tr><td colspan=\"2\" height=\"28\" align=\"center\"><div class=\"labelDiv\" onclick=\"selectLabel('" + mcs[i].Value + "'," + k.ToString() + ");\">" + getLabel1(mcs[i].Value) + mark + "</div></td></tr>";
        }
        //end

        BindLabel2();
    }

    //绑定内容标签
    protected void BindLabel2()
    {
        Regex rg = new Regex(@"<Whir:([a-zA-Z]+)[ ]+[^<>]*>");
        MatchCollection mcs = rg.Matches(this.txtHtml.Text);

        string attribute = @"(?:[\w-:]+)(?:=(?:[^\s\>\<]*|\""[\s\S]*?\""|\'[\s\S]*?\'))?";
        string name = @"(?:[\w-:]+)";
        string argument = @"=(?:[\w-:]+|\""[\s\S]*?\""|\'[\s\S]*?\')";
        Regex rgAttribute = new Regex(attribute);//属性
        Regex rgName = new Regex(name);//属性名称
        Regex rgArg = new Regex(argument);//属性值
        MatchCollection mc2;
        Match mc3, mc4;

        int width = 650, height = 410;
        foreach (Match match in mcs)
        {
            mc2 = rgAttribute.Matches(match.Value);
            foreach (Match ma in mc2)
            {
                mc3 = rgName.Match(ma.Value);
                if (mc3.Value.ToLower() == "id")
                {
                    mc4 = rgArg.Match(ma.Value);

                    string lid = mc4.Value.Substring(2, mc4.Value.Length - 3);
                    int first = match.Value.IndexOf(":") + 1;
                    string labelName = match.Value.Substring(first, match.Value.IndexOf(" ") - first);
                    switch (labelName)
                    {
                        case "UlList": width = 650; height = 410; break;
                        case "TableList": width = 650; height = 410; break;
                        case "Page": width = 500; height = 230; break;
                        case "Iframe": width = 500; height = 230; break;
                        case "FormLabel": width = 650; height = 320; break;
                    }
                    this.Literal1.Text += "<tr><td height=\"28\" align=\"center\"><div class=\"labelDiv\" onclick=\"selectLabel2('" + lid + "');\" title=\"" + lid + "\">" + getLabel2(mc2[0].Value) + "_" + lid + "</div></td><td width=\"10px\"><a onclick=\"editParam('" + labelName + "','" + lid + "'," + width + "," + height + ");\" style=\"color:blue;cursor:hand;\" title=\"编辑标签\">△</a></td></tr>";

                    break;
                }
            }
        }
    }

    //固定标签判断
    protected string getLabel1(string label)
    {
        int index = label.LastIndexOf('.');
        string name = label.Substring(index + 1, label.Length - index - 3);
        string v = "";

        switch (name)
        {
            case "SystemPath":
                v = "网站根路径";
                break;
            case "PicServer":
                v = "上传图片路径";
                break;
            case "ItemPicPath":
                v = "项目图片路径";
                break;
            case "SiteTitle":
                v = "网站标题 title";
                break;
            case "MetaKey":
                v = "网站关键字 keyword";
                break;
            case "MetaDesc":
                v = "网站描述 content";
                break;
            case "LogoUrl":
                v = "Logo 图";
                break;
            case "BannerUrl":
                v = "Banner 图";
                break;
            case "SiteICP":
                v = "站点 ICP";
                break;
            case "ICPUrl":
                v = "ICP 证书路径";
                break;
            case "Copyright":
                v = "版权";
                break;
            case "ADCatalog":
                v = "广告位";
                break;
            case "Email":
                v = "网站邮箱";
                break;
            default:
                v = "无效标签";
                break;
        }

        return v;
    }

    //内容标签判断
    protected string getLabel2(string label)
    {
        label = label.TrimEnd();
        string name = label.Substring(label.IndexOf(':') + 1);
        string v = "";

        name = name.ToLower();
        switch (name)
        {
            case "ullist":
                v = "Ul列表标签";
                break;
            case "tablelist":
                v = "Table列表标签";
                break;
            case "page":
                v = "分页标签";
                break;
            case "formlabel":
                v = "表单标签";
                break;
            case "menulabel":
                v = "菜单标签";
                break;
            case "slide":
                v = "幻灯片标签";
                break;
            case "iframe":
                v = "嵌套标签";
                break;
            default: break;
        }

        return v;
    }
    #endregion

    //保存
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //备份文件
        FileBackupHelper.Backup(Page, this.dir, Server.MapPath("~/UploadFiles/template/bak/"));

        Whir.Publish.CreateHtml.WriteFile(this.dir, this.txtHtml.Text);

        Response.Write("<script language=javascript>alert(\"模板修改成功\");window.opener=null;window.open(\"\",\"_self\");window.close();</script>");

        //this.OLAdd("修改模板", "保存模板修改");    //操作日志
    }

    //操作日志
    protected void OLAdd(string title, string desc)
    {
        Whir.Log.Model.Whir_OperateLog model = new Whir.Log.Model.Whir_OperateLog();
        model.title = title;
        model.operateType = 5;      //修改
        model.operateResult = true;
        model.operateDesc = desc;
        model.operateUrl = "Module/Template/TemplateList.aspx?dir=" + this.dir.Substring(0, this.dir.LastIndexOf('\\'));

        Whir.Log.OperateLog.Add(model);
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        btnDesign.Text = (btnDesign.Text == "设计") ? "代码" : "设计";
        if (btnDesign.Text == "设计")
        {
            Page.ClientScript.RegisterStartupScript(e.GetType(), "design", "<script>$('#controlPanel').reset();</script>");
            txtHtml.Style.Add("display", "");
            lblHtml.Style.Add("display", "none");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(e.GetType(), "source", "<script>$('#controlPanel').dragDefault();</script>");
            lblHtml.Text = tranLable(txtHtml.Text);
            lblHtml.Style.Add("display", "");
            txtHtml.Style.Add("display", "none");
        }
    }

    /// <summary>
    /// 解析呈现lable
    /// </summary>
    /// <param name="html"></param>
    /// <returns></returns>
    private string tranLable(string html)
    {
        Regex rg = new Regex(@"<Whir:([a-zA-Z]+)[ ]+[^<>]*>[\s\S]*?<\/Whir:\1>", RegexOptions.IgnoreCase);
        string[] str = rg.Split(html);
        MatchCollection lable = rg.Matches(html);
        StringBuilder sb = new StringBuilder();
        int j = 0;

        for (int k = 0; k < str.Length - 1; k++)
        {
            if (str[k] != lable[j].Groups[1].Value && str[k] != "")
            {
                sb.Append(str[k]);
                sb.Append("<div ID='tabadcontent_1" + j.ToString() + "'>");
                sb.Append(lable[j]);
                sb.Append("</div>");
            }
            else
            {
                if (str[k] != "") j++;
            }
        }

        sb.Append(str[str.Length - 1]);
        return sb.ToString();
    }

    protected void btnRestore_Click(object sender, EventArgs e)
    {
        if (this.ddlHistory.SelectedItem.Text != "暂无记录")
        {
            FileBackupHelper.Restore(Page,
             Server.MapPath("~/UploadFiles/template/bak/" + ddlHistory.SelectedItem.Text),
              Path.GetDirectoryName(this.dir) + "//");

            Response.Write("<script language=javascript>alert(\"模板还原成功\");window.opener=null;window.open(\"\",\"_self\");window.close();</script>");
        }
        else
        {
            Whir.Common.WebHelper.JsHelper.Alert("该文件暂无备份记录！");
        }
    }
}
